package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.QueryPageBeanCondition;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
	@Autowired
	private CheckGroupDao checkGroupDao;

	@Override
	public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
		checkGroupDao.add(checkGroup);
		this.setCheckGroupAndItem(checkGroup.getId(),checkitemIds);
	}

	@Override
	public PageResult pageQuery(QueryPageBeanCondition queryPageBeanCondition) {
		Integer currentPage = queryPageBeanCondition.getCurrentPage();
		Integer pageSize = queryPageBeanCondition.getPageSize();
		PageHelper.startPage(currentPage,pageSize);
		Page<CheckGroup> page =  checkGroupDao.selectByCondition(queryPageBeanCondition);
		long total = page.getTotal();
		List<CheckGroup> rows = page.getResult();
		return new PageResult(total,rows);
	}

//	@Override
//	public Result deleteById(Integer id) {
//		checkGroupDao.deleteRelationById(id);
//		checkGroupDao.deleteById(id);
//		return new Result();
//	}

	@Override
	public CheckGroup findGroupById(Integer id) {
		CheckGroup checkGroup = checkGroupDao.findGroupById(id);
		return checkGroup;
	}

	@Override
	public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
		//修改检查组基本信息
		checkGroupDao.edit(checkGroup);
		//清理关系表信息
		checkGroupDao.deleteRelationById(checkGroup.getId());
		//重新建立信息
		this.setCheckGroupAndItem(checkGroup.getId(),checkitemIds);

	}

	@Override
	public List<Integer> findItemById(Integer id) {

		List<Integer> checkitemIds = checkGroupDao.findItemById(id);
		return checkitemIds;
	}

	@Override
	public List<CheckGroup> findAll() {
		return checkGroupDao.findAll();
	}

	public void setCheckGroupAndItem(Integer checkGroupId, Integer[] checkitemIds) {
		if(checkitemIds!=null&&checkitemIds.length>0){
			for (Integer checkitemId : checkitemIds) {
				Map<String,Integer> map = new HashMap<>();
				map.put("checkgroup_id",checkGroupId);
				map.put("checkitem_id",checkitemId);
				checkGroupDao.setCheckGroupAndCheckItem(map);
			}
		}
	}
}
